package TCP.echoserver2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    Socket socket = null;

    public TcpEchoClient(String ip,int port) throws IOException {
        // 与服务器建立连接
        socket = new Socket(ip,port);
    }

    public void start(){
        try(InputStream inputStream = socket.getInputStream()){
            try(OutputStream outputStream = socket.getOutputStream()) {
                while (true) {
                    Scanner scanner = new Scanner(System.in);
                    String request = scanner.nextLine();
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(request);
                    printWriter.flush();

                    // 接受服务端的数据
                    Scanner scannerResponse = new Scanner(inputStream);
                    String response = scannerResponse.nextLine();
                    System.out.println(response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {

        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
